package com.express.e.root.servlet;



import com.express.e.root.handler.HandlerMapping;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 类说明：
 * 1.init方法：初始化得到web.xml文件存储的映射文件地址，加载为文件流，传递给映射池HandleMapping的load方法，初始化映射池
 * 2.service方法：将获取到的uri信息转为字符串，调用handlemapping方法,去映射池map中查找，找不到返回提示，找到的话，使用反射方法激活使用对象
 * 调用方法，将返回结果根据返回的注释类型返回不同的结果
 */
public class DispatcherServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.    获取用户请求的uri   /xx.do
        String uri = req.getRequestURI();
        HandlerMapping.MVCMapping mapping = HandlerMapping.getMapping(uri);
        if( mapping == null){
            resp.sendError(404,"MVC：映射地址不存在："+uri);
            return;
        }
        Object obj = mapping.getObj();
        Method method = mapping.getMethod();
        Object result = null;
        try {
            result = method.invoke(obj, req, resp);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        switch (mapping.getResponseType()){
            case TEXT:
                if (result != null) {
                    resp.getWriter().write((String)result);
                }
                break;
            case VIEW:
                if (result != null) {
                    req.getRequestDispatcher((String) result).forward(req,resp);
                }
                break;
        }
    }


    @Override
    public void init(ServletConfig config) throws ServletException {
        String contentConfigLocation = config.getInitParameter("applicationInitHandlerMappring");
        InputStream resourceAsStream = DispatcherServlet.class.getClassLoader().getResourceAsStream(contentConfigLocation);
        HandlerMapping.load(resourceAsStream);
    }
}
